import React, { Component, PropTypes } from 'react';
import { connect } from 'dva';
import { Table, Pagination, InputNumber, Dropdown, Button, Menu, Checkbox, Icon } from 'antd';
import filterItemCreate from './FilterItem'
import * as common from '../../utils/common'

class ReportTable extends React.Component {
    constructor(props) {
        super(props);
    }
    componentDidMount() {
        const { currentPage, pageSize, sorter, filters } = this.props;
        this.query({ page: currentPage, pageSize, sorter, filters })
    }
    rowClickHandler(d, i, e) {
        if (e.target.tagName === "TD") {
        }
    }
    pageChangeHandler(page) {
        const { pageSize, sorter, filters } = this.props;
        this.query({ page, pageSize, sorter, filters })
    }
    pageSizeChangeHandler(e) {
        const pageSize = parseInt(e.key)
        const { sorter, filters } = this.props;
        this.query({ page: 1, pageSize, sorter, filters })
    }
    reload() {
        const { currentPage, pageSize, sorter, filters } = this.props;
        this.query({ page: currentPage, pageSize, sorter, filters })
    }
    handleTableChange(_, filters2, sorter) {
        const { currentPage, pageSize, filters } = this.props;
        this.query({ page: currentPage, pageSize, sorter, filters })
    }
    query({ page, pageSize, sorter, filters }) {
        const model = this.props.model
        this.props.dispatch({
            type: `${model}/query`,
            payload: { page, pageSize, sorter, filters }
        });
    }
    handleFilterVisibleChange(name, visible) {
        if (!visible) {
            return
        }
        const model = this.props.model
        let filterName = null
        if (visible) {
            filterName = name
        }
        this.props.dispatch({
            type: `${model}/setVisibleFilterName`,
            payload: { visibleFilterName: filterName }
        });
    }
    getFilterDropdown(col) {
        const { model } = this.props;
        let cont = {
            label: col.title,
            name: col.key,
            type: col.dataType
        }
        const FilterItem = filterItemCreate(model, col.key)
        return <FilterItem daoName={model} control={cont} canSelectOR={false}/>
    }
    exportData() {
        const { page, pageSize, sorter, filters, hierarchy, list, selected, month } = this.props;
        var measures = []
        Object.keys(selected).map(tpid => {
            const meas = selected[tpid]
            measures.push(...meas)
        })
        const monthStart = common.formatMonth(month.start)
        const monthEnd = common.formatMonth(month.end)
        var req = {
            pageIndex: page,
            pageLineNum: pageSize,
            row: {
                "hierarchy": "部门.部门.部门",
                "sorts": [sorter],
                "filters": filters
            },
            column: {},
            measures: measures,
            context: [
                "{" + monthStart + ":" + monthEnd + "}"
            ]
        }
        let form = document.createElement('form');//定义一个form表单
        form.style = "display:none";
        form.target = "_blank";
        form.method = "post";
        form.action = "/api/BI/Export";
        let input1 = document.createElement("input");
        input1.type = "hidden";
        input1.name = "query";
        input1.value = JSON.stringify(req);
        document.body.appendChild(form);//将表单放置在web中
        form.appendChild(input1);
        form.submit();
        document.body.removeChild(form)
    }
    attachColumns(columns) {
        const { visibleFilterName, filters } = this.props
        const leafNode = col => {
            if (!col.children || col.children.lenght === 0) {
                col.filterDropdown = this.getFilterDropdown(col)
                let visible = false;
                if (col.key === visibleFilterName) {
                    visible = true;
                }
                col.filterDropdownVisible = visible;
                col.filteredValue = filters[col.key] ? [1] : [];
                col.onFilterDropdownVisibleChange = this.handleFilterVisibleChange.bind(this, col.key)
                col.sorter = true
                if (col.dataType === "number") {
                    col.className = "column-money"
                }
            } else {
                col.children.map(ccol => {
                    leafNode(ccol)
                })
            }
        }
        columns.map(col => {
            leafNode(col)
        })
    }
    getColumnsWidth(columns) {
        const getWidth = col => {
            if (!col.children || col.children.lenght === 0) {
                return col.width ? col.width : 90
            } else {
                let width = 0
                col.children.map(ccol => {
                    width = width + getWidth(ccol)
                })
                return width
            }
        }
        let width = 0
        columns.map(col => {
            width = width + getWidth(col)
        })
        return width
    }
    render() {
        const { columns, width, height, bordered, dataSource, loading, size, currentPage, pageSize, total, offsetHeight, offsetWidth, collapsedLeftMenu, keyName, selectedRowKeys, visibleFilterName, filters } = this.props;
        if (!columns || columns.lenght === 0) {
            return (<div></div>)
        }
        this.attachColumns(columns)
        let x = width, y = height
        if (width === 0) {
            x = this.getColumnsWidth(columns)
        }
        if (height === 0) {
            y = offsetHeight - 175 - 42
            if (x > offsetWidth) {
                y = y - 20
            }
        }
        const menu2 = (<Menu onClick={this.pageSizeChangeHandler.bind(this)}>
            <Menu.Item key="10">每页显示10行</Menu.Item>
            <Menu.Item key="20">每页显示20行</Menu.Item>
            <Menu.Item key="30">每页显示30行</Menu.Item>
            <Menu.Item key="40">每页显示40行</Menu.Item>
            <Menu.Item key="50">每页显示50行</Menu.Item>
        </Menu>);
        let exportButton = ""
        if (this.props.canExport) {
            exportButton = <Button style={{ margin: 5 }} key="b_exportData" onClick={this.exportData.bind(this)}>导出excel</Button>
        }
        return (
            <div>
                <Table
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    onRowClick={this.rowClickHandler.bind(this)}
                    rowKey={record => record[keyName]}
                    scroll={{ x, y }}
                    bordered={bordered}
                    pagination={false}
                    size={size}
                    onChange={this.handleTableChange.bind(this)}
                />
                <div>
                    <Dropdown overlay={menu2} trigger={['click']} >
                        <Button type="ghost" style={{ margin: 5 }}>
                            每页显示{pageSize}行 <Icon type="down" />
                        </Button>
                    </Dropdown>
                    {exportButton}
                    <Pagination style={{ margin: '5px 5px' }}
                        className="ant-table-pagination"
                        total={total}
                        current={currentPage}
                        pageSize={pageSize}
                        onChange={this.pageChangeHandler.bind(this)}
                    />
                </div>
            </div>
        );
    }
}
ReportTable.propTypes = {
    width: PropTypes.number,
    height: PropTypes.number,
    bordered: PropTypes.bool,
    size: PropTypes.string,
    canExport: PropTypes.bool,
};
ReportTable.defaultProps = {
    width: 0,
    height: 0,
    bordered: true,
    size: "middle",
    canExport: true,
};

export default function reportTableCreate(model) {
    function mapStateToProps(state) {
        const { tableData, page, sorter, filters, visibleFilterName, hierarchy } = state[model];
        const { offsetHeight, offsetWidth, collapsedLeftMenu } = state.menus
        return {
            model: model,
            loading: state.loading.models[model],
            columns: tableData.columns,
            dataSource: tableData.dataList,
            total: tableData.total,
            currentPage: page.index,
            pageSize: page.lineNum,
            sorter: sorter,
            filters: filters,
            hierarchy,
            offsetHeight,
            offsetWidth,
            collapsedLeftMenu,
            visibleFilterName
        }
    }
    return connect(mapStateToProps)(ReportTable);
}
